﻿using Fast.NormalizeActionResult;
using Fast.Validation;
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.DependencyInjection;

namespace Fast.ExceptionHandling
{
    /// <summary>
    /// 异常元数据转换器
    /// </summary>
    public class DefaultExceptionMetadataConverter : IExceptionMetadataConverter, ITransientDependency
    {
        public virtual ExceptionMetadata Convert(Exception exception)
        {
            var metadata = new ExceptionMetadata("发生了未知的内部错误");

            if (exception is UserFriendlyException userFriendlyException)
            {
                metadata.Message = userFriendlyException.Message;
                metadata.Code = userFriendlyException.Code;
            }
            if (exception is BusinessException businessException)
            {
                metadata.Message = businessException.Message;
                metadata.Code = businessException.Code;
            }
            if (exception is FastValidationException validationException)
            {
                metadata.Message = validationException.Message;
                metadata.ValidationErrors = GetValidationErrorInfos(validationException);
            }
            return metadata;
        }


        protected virtual ValidationErrorInfo[] GetValidationErrorInfos(IHasValidationErrors validationException)
        {
            var validationErrorInfos = new List<ValidationErrorInfo>();

            foreach (var validationResult in validationException.ValidationErrors)
            {
                var validationError = new ValidationErrorInfo(validationResult.ErrorMessage);

                if (validationResult.MemberNames != null && validationResult.MemberNames.Any())
                {
                    validationError.Members = validationResult.MemberNames.Select(m => m).ToArray();
                }

                validationErrorInfos.Add(validationError);
            }

            return validationErrorInfos.ToArray();
        }
    }
}
